package org.excilys.training.ebanking.DTO;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;

import org.excilys.training.ebanking.iservice.IServiceCompte;
import org.excilys.training.ebanking.iservice.IServiceTypeOperation;
import org.excilys.training.ebanking.model.Operation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ebanking_ws_soap.ebankingvirement.OperationDTO;

@Repository
public class FactoryDTO implements IFactoryDTO {

	@Autowired
	private IServiceTypeOperation serviceTypeOperation;

	@Autowired
	private IServiceCompte serviceCompte;
	@Override
	public OperationDTO createOPerationDTO(Operation operation) {
		OperationDTO operationdto = new OperationDTO();

		operationdto.setCompteDestinataire(operation.getCompteDestinataire());
		operationdto.setId(operation.getId());
		operationdto.setIdcompte(operation.getCompte().getId());
		operationdto.setMontant(Double.valueOf(operation.getMontant()).floatValue());
		operationdto.setLibelle(operation.getLibelle());
		operationdto.setIdTypeOperation(operation.getTypeOperation().getId());
		GregorianCalendar gc = new GregorianCalendar();
		Date dateOperation = operation.getDateOperation().toDate();
		gc.setTime(dateOperation);
		try {
			operationdto.setDateOperation(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
		} catch (DatatypeConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		return operationdto;
	}

	public Operation createOperation(OperationDTO operationdto){
		Operation operation = new Operation();

		Date date = operationdto.getDateOperation().toGregorianCalendar().getTime();

		operation.setCompte(serviceCompte.getAccount(operationdto.getIdcompte()));
		operation.setCompteDestinataire(operationdto.getCompteDestinataire());
		operation.setId(operationdto.getId());
		operation.setLibelle(operation.getLibelle());
		operation.setMontant(operationdto.getMontant());
		operation.setTypeOperation(serviceTypeOperation.getTypeOperation(operationdto.getIdTypeOperation()));
		operation.setDateOperation(new DateTime(date));


		return operation;
	}
}
